<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传聊天框</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body, html {
            height: 100%;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
        }

        .chat-container {
            display: flex;
            flex-direction: column;
            height: 100%;
            background-color: white;
            position: relative;
            overflow: hidden;
        }

        .main-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: flex-start;
            padding-top: 15vh;
            flex: 1;
            overflow-y: auto;
            padding-bottom: 20px;
        }

        .upload-btn {
            background-color: #3a6bc8;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 20px 40px;
            font-size: 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 12px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            min-width: 280px;
            margin-bottom: 20px;
            position: relative;
        }

        .upload-btn:hover {
            background-color: #2c5bb4;
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
        }

        .upload-btn-icons {
            display: none;
            margin-left: 10px;
            gap: 8px;
        }

        .upload-btn-icons i {
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .upload-btn-icons i:hover {
            transform: scale(1.1);
        }

        .upload-btn-icons .fa-paper-plane:hover {
            color: #2ecc71;
        }

        .upload-btn-icons .fa-trash-alt:hover {
            color: #e74c3c;
        }

        .file-input {
            display: none;
        }

        .messages-container {
            width: 100%;
            max-width: 600px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .success-message {
            color: #3a6bc8;
            font-size: 14px;
            margin: 10px 0;
            text-align: center;
            display: none;
            animation: messageAppear 0.3s ease-out;
        }

        .training-message {
            color: #6a5acd;
            font-size: 14px;
            margin: 5px 0 15px 0;
            text-align: center;
            display: none;
        }

        .next-btn {
            background-color: #2ecc71;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 12px 24px;
            margin: 15px 0;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 16px;
        }

        .next-btn:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }

        .next-btn:hover:not(:disabled) {
            background-color: #27ae60;
        }

        .parameter-input-container {
            width: 350px;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
            margin: 15px 0;
            display: none;
            animation: messageAppear 0.5s ease-out;
        }

        .parameter-item {
            margin-bottom: 15px;
        }

        .parameter-label {
            font-weight: bold;
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-size: 15px;
        }

        .parameter-input {
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 100%;
            font-size: 15px;
        }

        .parameter-input:focus {
            outline: none;
            border-color: #3a6bc8;
            box-shadow: 0 0 0 2px rgba(58, 107, 200, 0.2);
        }

        .system-message {
            color: #0066cc;
            margin: 10px 0;
            text-align: center;
            max-width: 80%;
            padding: 0;
            font-size: 14px;
            line-height: 1.5;
            animation: messageAppear 0.3s ease-out;
        }

        .param-next-btn-container {
            text-align: center;
            margin-top: 20px;
        }

        .button-group {
            display: flex;
            gap: 15px;
            align-items: center;
            justify-content: center;
            margin-top: 15px;
        }

        .reupload-btn {
            background-color: #e74c3c;
            color: white;
            border: none;
            border-radius: 50px;
            padding: 12px 24px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 16px;
            display: none;
        }

        .reupload-btn:hover {
            background-color: #c0392b;
        }

        @keyframes messageAppear {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .parameter-input {
            /* 新增下拉框样式 */
            appearance: none;
            -webkit-appearance: none;
            background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23333'%3E%3Cpath d='M7 10l5 5 5-5z'/%3E%3C/svg%3E") no-repeat right 12px center/15px 15px;
        }
    </style>
</head>
<body>
<div class="chat-container">
    <div class="main-content" id="mainContent">
        <button class="upload-btn" id="uploadBtn">
            <i class="fas fa-paperclip"></i>
            <span id="uploadBtnText">上传评估文件</span>
            <span class="upload-btn-icons" id="uploadBtnIcons">
                <i class="fas fa-paper-plane" id="sendIcon" title="上传文件"></i>
                <i class="fas fa-trash-alt" id="trashIcon" title="取消选择"></i>
            </span>
        </button>
        <input type="file" id="fileInput" class="file-input" accept=".csv,.txt,.json">

        <div class="messages-container" id="messagesContainer">
            <!-- 动态消息将在这里显示 -->
        </div>

        <div class="button-group" id="buttonGroup">
            <button class="reupload-btn" id="reuploadBtn">
                <i class="fas fa-redo"></i> 重新上传文件
            </button>
            <button class="next-btn" id="nextBtn" style="display: none;">下一步</button>
        </div>

        <div class="parameter-input-container" id="parameterContainer">
            <div class="parameter-item">
                <label class="parameter-label" for="epochSelect">选择你的模型</label>
                <select class="parameter-input" id="epochSelect">
                    <option value="" disabled selected>正在加载可用模型...</option>
                </select>
            </div>
            <div class="param-next-btn-container">
                <button class="next-btn" id="paramNextBtn" disabled>开始预测</button>
            </div>
        </div>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // DOM元素获取
        const uploadBtn = document.getElementById('uploadBtn');
        const uploadBtnText = document.getElementById('uploadBtnText');
        const uploadBtnIcons = document.getElementById('uploadBtnIcons');
        const fileInput = document.getElementById('fileInput');
        const messagesContainer = document.getElementById('messagesContainer');
        const nextBtn = document.getElementById('nextBtn');
        const reuploadBtn = document.getElementById('reuploadBtn');
        const parameterContainer = document.getElementById('parameterContainer');
        const paramNextBtn = document.getElementById('paramNextBtn');
        const epochSelect = document.getElementById('epochSelect');
        const epochNamesFromServer = {{ epoch_data|safe }};  // 更新为包含id和name的完整数据
        const current_user = "{{ username }}";  // 使用模板变量获取当前用户名

        let selectedFile = null;

        // WebSocket连接
        const socket = new WebSocket('ws://' + window.location.host + '/ws/predict/');
        const resultsocket = new WebSocket('ws://' + window.location.host + '/ws/results/?page=predictchat');

        // 通知父页面函数
        function notifyParentToStep(step, action) {
            try {
                window.parent.postMessage({
                    type: 'proceed_to_step',
                    step: step,
                    action: action
                }, '*');
            } catch (e) {
                console.error('通知父页面失败:', e);
            }
        }

        // 重新上传功能函数
        async function resetUploadState() {
            try {
                if (selectedFile) {
                    const deleteData = {
                        type: 'reupload_file',
                        filename: selectedFile.name
                    };
                    socket.send(JSON.stringify(deleteData));
                }
            } catch (e) {
                console.error('删除文件失败:', e);
                addSystemMessage('删除旧文件失败: ' + e.message);
            }

            selectedFile = null;
            fileInput.value = '';
            uploadBtnText.textContent = '上传预测文件';
            uploadBtnIcons.style.display = 'none';
            nextBtn.style.display = 'none';
            reuploadBtn.style.display = 'none';
            parameterContainer.style.display = 'none';
            messagesContainer.innerHTML = '';

            epochSelect.innerHTML = '<option value="" disabled selected>正在重新加载...</option>';

            // 通知父页面
            notifyParentToStep(1, 'reupload_file');
            addSystemMessage('已重置上传状态，请重新选择文件');

            socket.send(JSON.stringify({ type: 'get_epochs' }));
        }

        reuploadBtn.addEventListener('click', async function() {
            await resetUploadState();
            this.classList.add('processing');
            setTimeout(() => {
                this.classList.remove('processing');
            }, 500);
        });

        socket.onopen = function(e) {
            console.log('WebSocket连接已建立');
            addSystemMessage('服务器连接成功');
        };

        socket.onmessage = function(e) {
            const data = JSON.parse(e.data);

            if (data.type === 'status') {
                addSystemMessage(data.message);
            } else if (data.type === 'error') {
                addSystemMessage('错误: ' + data.message);
            }
        };

        // 修改后的填充模型选择函数
    function populateEpochSelect(models) {
        const epochSelect = document.getElementById('epochSelect');
        epochSelect.innerHTML = '';

        if (!models || models.length === 0) {
            const option = document.createElement('option');
            option.value = '';
            option.textContent = '暂无可用模型';
            option.disabled = true;
            option.selected = true;
            epochSelect.appendChild(option);
            addSystemMessage('请选择模型...');
            return;
        }

        // 添加默认提示选项
        const defaultOption = document.createElement('option');
        defaultOption.value = '';
        defaultOption.textContent = '请选择模型...';
        defaultOption.disabled = true;
        defaultOption.selected = true;
        epochSelect.appendChild(defaultOption);

        // 添加模型选项
        models.forEach(model => {
            const option = document.createElement('option');
            option.value = model.id;
            option.textContent = model.name;
            epochSelect.appendChild(option);
        });

        // 启用选择器
        epochSelect.disabled = false;
        checkEpochSelected();
    }

        function checkEpochSelected() {
    const selected = epochSelect.value !== '';
    paramNextBtn.disabled = !selected;
    paramNextBtn.style.backgroundColor = selected ? '#2ecc71' : '#95a5a6';
    return selected;
}

        function uploadFile() {
            if (!selectedFile) {
                addSystemMessage('请先选择文件');
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                const fileData = {
                    type: 'file_upload',
                    name: selectedFile.name,
                    content: e.target.result
                };

                socket.send(JSON.stringify(fileData));
                nextBtn.style.display = 'block';
                reuploadBtn.style.display = 'block';
                uploadBtnIcons.style.display = 'none';
            };
            reader.readAsText(selectedFile);
        }

        uploadBtn.addEventListener('click', () => !selectedFile && fileInput.click());

        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                selectedFile = this.files[0];
                uploadBtnText.textContent = selectedFile.name;
                uploadBtnIcons.style.display = 'flex';
                addSystemMessage(`已选择文件: ${selectedFile.name}`);
            }
        });

        document.getElementById('sendIcon').addEventListener('click', uploadFile);

        document.getElementById('trashIcon').addEventListener('click', () => {
            selectedFile = null;
            fileInput.value = '';
            uploadBtnText.textContent = '上传预测文件';
            uploadBtnIcons.style.display = 'none';
            addSystemMessage('已取消文件选择');
            notifyParentToStep(1, 'reupload_file');
        });

        nextBtn.addEventListener('click', () => {
            notifyParentToStep(2, 'file_uploaded');
            parameterContainer.style.display = 'block';
            nextBtn.style.display = 'none';
            populateEpochSelect(epochNamesFromServer); // 调用模型填充函数
        });

        paramNextBtn.addEventListener('click', function() {
    const selectedEpochId = epochSelect.value;
    const selectedEpoch = epochNamesFromServer.find(model => model.id == selectedEpochId);
    const selectedEpochName = selectedEpoch ? selectedEpoch.name : '';

    // 隐藏重新上传按钮
    reuploadBtn.style.display = 'none';
    // 禁用并修改开始预测按钮
    this.disabled = true;
    this.style.backgroundColor = '#95a5a6';
    this.textContent = `已选择模型: ${selectedEpochName}`;

    const predictionData = {
        type: 'start_prediction',
        model_id: selectedEpochId,
        model_name: selectedEpochName,
        username: current_user
    };

    resultsocket.send(JSON.stringify(predictionData));
    notifyParentToStep(3, 'parameters_submitted');
});

        // 辅助函数
        function addSystemMessage(text) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'system-message';
            messageDiv.textContent = text;
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

       window.addEventListener('message', function(event) {
    console.log("收到消息完整内容:", event.data);

    if (event.data.type === 'ajax_response') {
        const res = event.data.response;
        console.log("解析后的响应数据:", res);


        // 2. 填充下拉框（直接操作DOM，避免依赖外部变量）
        const epochSelect = document.getElementById('epochSelect');
        epochSelect.innerHTML = ''; // 清空现有选项

        if (!res.epoch_data || !Array.isArray(res.epoch_data)) {
            console.error("无效的 epoch_data:", res.epoch_data);
            epochSelect.innerHTML = '<option value="" disabled>数据格式错误</option>';
            return;
        }

        // 添加默认提示选项
        const defaultOption = document.createElement('option');
        defaultOption.value = '';
        defaultOption.textContent = '请选择模型...';
        defaultOption.disabled = true;
        defaultOption.selected = true;
        epochSelect.appendChild(defaultOption);

        // 添加模型选项
        res.epoch_data.forEach(epoch => {
            const option = document.createElement('option');
            option.value = epoch.id;      // 确保字段名匹配
            option.textContent = epoch.name; // 确保字段名匹配
            epochSelect.appendChild(option);
        });

        // 3. 显示参数区域
        document.getElementById('parameterContainer').style.display = 'block';
    }
});
epochSelect.addEventListener('change', function() {
    checkEpochSelected();
});

    });
</script>
</body>
</html>